$(function (){
    // defined constant
    let MESSAGE_TYPE;
    let EXCLUDE_SITE_LSIT = [];

    // init enum
    chrome.storage.sync.get(['messageType', 'excludeSiteList']).then((result) => {
        MESSAGE_TYPE = result.messageType;
        EXCLUDE_SITE_LSIT = result.excludeSiteList;

        refreshSiteListPage();
        document.getElementById("fl-option-add-button").addEventListener("click", optionAdd);
        document.getElementById("fl-option-del-button").addEventListener("click", optionDel);
    });

    async function syncPage(){
        chrome.storage.sync.set({
            excludeSiteList: EXCLUDE_SITE_LSIT
        });
        chrome.tabs.query({ active: true,currentWindow: true}, function(tabs) {
            if (tabs.length > 0) {
                let activeTab = tabs[0];
                (async () => {
                    await chrome.tabs.sendMessage(activeTab.id, getMessage(MESSAGE_TYPE.UPDATE_EXCLUDE_SITE, null));
                })();
            }
        });
    }

    // 添加需要排除的网页
    function optionAdd(){
        EXCLUDE_SITE_LSIT.push($("#fl-otion-add-con").val());
        $("#fl-otion-add-con").val("");
        refreshSiteListPage();
        syncPage();
    }

    // 删除需要排除的网页
    function optionDel(){
        EXCLUDE_SITE_LSIT = [];
        for(var i = 0;i < $("#fl-option-list").find("input:checkbox").length;i ++){
            if($("#fl-option-list").find("input:checkbox").eq(i).prop('checked') == false){
                EXCLUDE_SITE_LSIT.push($("#fl-option-list").find("input:checkbox").eq(i).val());
            }
        }
        refreshSiteListPage();
        syncPage();
    }

    // 刷新排除网站列表界面
    function refreshSiteListPage(){
        $("#fl-option-list").html("");
        let htmlStr = "";
        for(var i = 0;i < EXCLUDE_SITE_LSIT.length;i ++){
            htmlStr += '<label><input type="checkbox" value="' + EXCLUDE_SITE_LSIT[i] + '"/>' + EXCLUDE_SITE_LSIT[i] + '</label>';
        }
        $("#fl-option-list").append(htmlStr);
    }

    // 插件内部通讯实体
    function getMessage(messageType, messageData){
        return {
            type: messageType,
            data: messageData
        };
    }
});